﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Enter.Mvc.Base.Controllers;
using Enter.Services.DataCache;
using Enter.Services.Mail;
using System.Web.Mvc;
using Enter.Entity;
using Enter.Mvc.Mall.Model.User;
using Enter.Mvc.Mall.Model;
using Enter.Mvc.Mall.Model.Order;
using System.Data;
using Enter.Common;
using Enter.Config;
using Newtonsoft.Json;
using System.Collections.Specialized;

namespace Enter.Mvc.Mall.Controllers
{
    public class OrderController : BaseControllers
    {
         private readonly ICache icache;
        private readonly IMail imail;

        public OrderController(ICache cache, IMail mail)
        {
            this.icache = cache;
            this.imail = mail;
            T201_UserEntity UserLogin = imail.GetUserByName("tongli");

            UserInfo user = new UserInfo();
            user.UserID = UserLogin.UIID;
            user.UserName = UserLogin.UName;
            user.ShopNo = UserLogin.ShopNo;
            user.UserType = (UserInfo.EnumUserType)(int)UserLogin.UserType;
            UserInfo.CurrentUser = user;
        }
        public ActionResult AddCart(string gID, string gItemID, string count,string shopNO)
        {
           
            var results = new JsonResultModel();
            try
            {
                T303_Order_CartEntity entity = new T303_Order_CartEntity();
                entity.UID = UserInfo.CurrentUser.UserID;
                entity.ShopNO = shopNO;
                entity.GID = int.Parse(gID);
                entity.GItemID =int.Parse(gItemID);
                entity.ONUM = int.Parse(count);
                if (imail.AddCar(entity))
                {
                    results.ResultCode = "00";
                    results.ResultMsg = "成功";
                }
                else {
                    results.ResultCode = "01";
                    results.ResultMsg = "失败";
                }
                
            }
            catch (Exception ex)
            {

                results.ResultCode = "01";
                results.ResultMsg = ex.Message;
            }

            return Json(results);
        }

        #region 获取购物车
        public ActionResult myCart()
        {
            return View();
        }

        public ActionResult GetCart()
        {
            DataTable dt = imail.GetUserCar(UserInfo.CurrentUser.UserID);
            DataRow[] drdel = dt.Select(string.Format("Status={0}", (int)Enter.Entity.T303_Order_CartEntity.EnumStatus.Del), "addtime desc");
           string delcartids = "";
            if(drdel.Count<DataRow>()>0)
            {
                foreach(DataRow dr in drdel)
                {
                    delcartids += dr["ID"].ToString()+"|";
                }
            
            }
           DataRow[] drs = dt.Select(string.Format("Status={0}", (int)Enter.Entity.T303_Order_CartEntity.EnumStatus.Valid));
            List<MyCart> mycart = null;
            if (drs != null)
            {
                mycart = new List<MyCart>();

                foreach (DataRow dr in drs)
                {
                    string shopNo = dr["ShopNO"].ToString();
                    MyCart cart = mycart.Find(m => m.ShopNO == shopNo);
                    if (cart == null)
                    {
                        cart = new MyCart();
                        cart.ShopNO = shopNo;
                        cart.ShopName = dr["SName"].ToString();
                        List<CartModel> ps = new List<CartModel>();
                        CartModel p = ProdModel(dr);
                        ps.Add(p);
                        cart.Product = ps;
                        mycart.Add(cart);
                    }
                    else
                    {
                        CartModel p = ProdModel(dr);

                        cart.Product.Add(p);
                    }
                }
            }
          
            object obj = new { list = mycart, delcartids = delcartids.TrimEnd('|') };
            string result = JavaScriptConvert.SerializeObject(obj);
            return Content(result);
        }


        public ActionResult GetOrderCart(string ids)
        {
            DataTable dt = imail.GetUserCar(UserInfo.CurrentUser.UserID, ids);
            DataRow[] drdel = dt.Select(string.Format("Status={0}", (int)Enter.Entity.T303_Order_CartEntity.EnumStatus.Del), "addtime desc");
            string delcartids = "";
            if (drdel.Count<DataRow>() > 0)
            {
                foreach (DataRow dr in drdel)
                {
                    delcartids += dr["ID"].ToString() + "|";
                }

            }
            DataRow[] drs = dt.Select(string.Format("Status={0}", (int)Enter.Entity.T303_Order_CartEntity.EnumStatus.Valid));
           
            List<MyCart> mycart = getMyCart(drs, out ids);
            

            object obj = new { list = mycart, delcartids = delcartids.TrimEnd('|') };
            string result = JavaScriptConvert.SerializeObject(obj);
            return Content(result);
        }

        public ActionResult UpdateCartNum(string cartID, string num)
        {
            var results = new JsonResultModel();
            try
            {

                if (imail.UpdateCartCount(int.Parse(cartID),UserInfo.CurrentUser.UserID, int.Parse(num)))
                {
                    results.ResultCode = "00";
                    results.ResultMsg = "修改成功";
                }

            }
            catch (Exception ex)
            {

                results.ResultCode = "01";
                results.ResultMsg = ex.Message;
            }



            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return Json(results);
        }
        public ActionResult DelProd(string cartID)
        {
            imail.UpdateCartStatus(cartID,UserInfo.CurrentUser.UserID, Enter.Entity.T303_Order_CartEntity.EnumStatus.Del);
          return  GetCart();
        }

        public ActionResult CancelDelProd(string cartID)
    {
        imail.UpdateCartStatus(cartID,UserInfo.CurrentUser.UserID, Enter.Entity.T303_Order_CartEntity.EnumStatus.Valid);
        return GetCart();
    }
        public ActionResult DelNoValid(string cartID)
        {
            imail.DelCart(cartID, UserInfo.CurrentUser.UserID);
            return GetCart();
        }
        #region 装车
        private List<MyCart> getMyCart(DataRow[] drs, out string ids)
        {
            ids = "";
            List<MyCart> mycart = null;
            if (drs != null)
            {
                mycart = new List<MyCart>();

                foreach (DataRow dr in drs)
                {
                    ids += string.Format("{0},", dr["ID"].ToString());
                    string shopNo = dr["ShopNO"].ToString();
                    MyCart cart = mycart.Find(m => m.ShopNO == shopNo);
                    if (cart == null)
                    {
                        cart = new MyCart();
                        cart.ShopNO = shopNo;
                        cart.ShopName = dr["SName"].ToString();
                        List<CartModel> ps = new List<CartModel>();
                        CartModel p = ProdModel(dr);
                        ps.Add(p);
                        cart.Product = ps;
                        mycart.Add(cart);
                    }
                    else
                    {
                        CartModel p = ProdModel(dr);

                        cart.Product.Add(p);
                    }
                }
                ids = ids.TrimEnd(',');
            }
            return mycart;
        }
        private CartModel ProdModel(DataRow dr)
        {
            CartModel p = new CartModel();
            p.ID = SafeConvert.ToInt32(dr["ID"].ToString());
            p.GID = SafeConvert.ToInt32(dr["GID"].ToString());
            p.Title = dr["GTitle"].ToString();
            p.ImgUrl = ImgPathConfig.productListServerPath + dr["ImgUrl"].ToString();
            p.SmallImgUrl = ImgPathConfig.productInfoServerPath + dr["SmallImgUrl"].ToString();
            p.OPRICE = SafeConvert.ToDecimal(dr["SalePRICE"]);
            p.Status = 1;
            p.GItemID = SafeConvert.ToInt32(dr["GItemID"].ToString());
            p.ONUM = SafeConvert.ToInt32(dr["onum"].ToString());
            p.Stock = SafeConvert.ToInt32(dr["STOCKS"].ToString());
            if (SafeConvert.ToInt32(dr["STOCKS"].ToString()) == 0 || SafeConvert.ToDateTime(dr["GEndTime"].ToString()) < DateTime.Now )
            {
                p.Status = 0;
            }
           
            
            if (p.GItemID != 0)
            {
                T103_Goods_ItemEntity item = imail.getProductItemInfo(p.GItemID);
              
                p.Color = item.ColorName;
                p.Size = item.SizeName; 
                if (string.IsNullOrEmpty(item.ColorName))
                {
                    p.Color = "";
                }
                if (string.IsNullOrEmpty(item.SizeName))
                {
                    p.Size = "";
                }
                p.OPRICE = item.PSalePRICE;
                if (item.GSTOCKS == 0)
                {
                    p.Status = 0;
                }
            }
            return p;
        }
        /// <summary>
        /// 获取失效商品
        /// </summary>
        /// <param name="drs"></param>
        /// <returns></returns>
        private List<MyCart> getMyCart_NoValid(DataRow[] drs, out string ids)
        {
            ids = "";
            List<MyCart> mycart = null;
            if (drs != null)
            {
                mycart = new List<MyCart>();

                foreach (DataRow dr in drs)
                {

                    ids += string.Format("{0},", dr["ID"].ToString());
                    string shopNo = dr["ShopNO"].ToString();
                    MyCart cart = mycart.Find(m => m.ShopNO == shopNo);
                    if (cart == null)
                    {
                        cart = new MyCart();
                        cart.ShopNO = shopNo;
                        cart.ShopName = dr["SName"].ToString();
                        List<CartModel> ps = new List<CartModel>();
                        CartModel p = ProdModel_NoValid(dr);
                        ps.Add(p);
                        cart.Product = ps;
                        mycart.Add(cart);
                    }
                    else
                    {
                        CartModel p = ProdModel_NoValid(dr);

                        cart.Product.Add(p);
                    }
                }
                ids = ids.TrimEnd(',');
            }
            return mycart;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        private CartModel ProdModel_NoValid(DataRow dr)
        {
            CartModel p = new CartModel();
            p.ID = SafeConvert.ToInt32(dr["ID"].ToString());
            p.GID = SafeConvert.ToInt32(dr["GID"].ToString());
            p.Title = dr["GTitle"].ToString();
            p.ImgUrl = ImgPathConfig.productListServerPath + dr["ImgUrl"].ToString();
            p.SmallImgUrl = ImgPathConfig.productInfoServerPath + dr["SmallImgUrl"].ToString();
            p.OPRICE = SafeConvert.ToDecimal(dr["SalePRICE"]);
            p.Status = 1;
            p.GItemID = SafeConvert.ToInt32(dr["GItemID"].ToString());
            p.ONUM = SafeConvert.ToInt32(dr["onum"].ToString());
            p.Stock = SafeConvert.ToInt32(dr["STOCKS"].ToString());  
            if(p.ONUM>p.Stock)
            {
                p.Status = 0;
                p.Msg = "对不起，您输入的数量超过了可购买的最大数量!";
            }
            if (SafeConvert.ToInt32(dr["STOCKS"].ToString()) == 0 )
            {
                p.Status = 0;
                p.Msg = "对不起，该商品已售完!";
            }
            if (SafeConvert.ToDateTime(dr["GEndTime"].ToString()) < DateTime.Now )
            {
                p.Status = 0;
                p.Msg = "对不起，该商品已下架!";
            }
          

            if (p.GItemID != 0)
            {
                T103_Goods_ItemEntity item = imail.getProductItemInfo(p.GItemID);

                p.Color = item.ColorName;
                p.Size = item.SizeName;
                if (string.IsNullOrEmpty(item.ColorName))
                {
                    p.Color = "";
                }
                if (string.IsNullOrEmpty(item.SizeName))
                {
                    p.Size = "";
                }
                p.OPRICE = item.PSalePRICE;
                if (item.GSTOCKS == 0)
                {
                    p.Status = 0;
                }
            }
            return p;
        }
        #endregion
        #endregion

        #region 确认订单
        public ActionResult confirm_order()
        {
            return View();
        }
        [HttpPost]
        public ActionResult order_result()
        {
           
            string encryptString =RequestStrHelper.GetStringFromRequest("encryptString");
            string cartIds = RequestStrHelper.GetStringFromRequest("cartIds");

            string deliverId = RequestStrHelper.GetStringFromRequest("deliverId");
            string deliverName = RequestStrHelper.GetStringFromRequest("deliverName");
            string deliverMobile = RequestStrHelper.GetStringFromRequest("deliverMobile");
            string deliverCode = RequestStrHelper.GetStringFromRequest("deliverCode");
            string deliverAddr = RequestStrHelper.GetStringFromRequest("deliverAddr");
            string postCode = RequestStrHelper.GetStringFromRequest("postCode");


            DataTable dt = imail.GetUserCar(UserInfo.CurrentUser.UserID, cartIds);

            List<T301_Order_MainEntity> list = new List<T301_Order_MainEntity>();
            foreach (DataRow dr in dt.Rows)
            {
                string shopNo = dr["ShopNO"].ToString();
                T301_Order_MainEntity order = list.Find(m => m.SNO == shopNo);
                if (order == null)
                {
                    order = new T301_Order_MainEntity();
                    order.OMOrderNO = imail.GetOrderNo();
                    order.SNO = shopNo;
                    order.OYunFei = 0;
                    order.UIID = UserInfo.CurrentUser.UserID;
                    order.OSTATE = EnumOrderStatus.NOT_PAID;
                    order.OAddTime = DateTime.Now;
                    order.Memo = RequestStrHelper.GetStringFromRequest(order.SNO+"|memo");
                    List<T302_Order_ItemsEntity> items = new List<T302_Order_ItemsEntity>();
                    
                    T302_Order_ItemsEntity item = new T302_Order_ItemsEntity();

                  
          

                    item.GID=SafeConvert.ToInt32(dr["GID"].ToString());
                    item.GItemID=dr["GItemID"].ToString();
                    item.ONUM=SafeConvert.ToInt32(dr["onum"].ToString());
                    item.OPRICE=SafeConvert.ToDecimal(dr["SalePRICE"]);
                    order.OGoodAmount += item.ONUM * item.OPRICE;
                    order.OAMOUNT = order.OGoodAmount + order.OYunFei;
                    items.Add(item);
                    order.items = items;
                    list.Add(order);
                }
                else
                {
                    T302_Order_ItemsEntity item = new T302_Order_ItemsEntity();
                    item.GID = SafeConvert.ToInt32(dr["GID"].ToString());
                    item.GItemID = dr["GItemID"].ToString();
                    item.ONUM = SafeConvert.ToInt32(dr["onum"].ToString());
                    item.OPRICE = SafeConvert.ToDecimal(dr["SalePRICE"]);
                    order.OGoodAmount += item.ONUM * item.OPRICE;
                    order.OAMOUNT = order.OGoodAmount + order.OYunFei;
                    order.items.Add(item);
                }
            }
            imail.AddUserOrder(list);

            return View();
        }

        [HttpPost]
        public ActionResult confirm_order(string ids)
        {
            DataTable dt = imail.GetUserCar(UserInfo.CurrentUser.UserID, ids);

            DataRow[] NoVs = dt.Select(string.Format("STOCKS=0 or onum>STOCKS or GEndTime<'{0}'",DateTime.Now));
            
            string noids = "";
            List<MyCart> Nomycart = getMyCart_NoValid(NoVs,out noids);
            DataRow[] drs ;

            if (string.IsNullOrEmpty(noids))
            {
                drs=dt.Select("");
            }
            else
            {
                drs = dt.Select(string.Format("ID not in ({0})",noids));
            }
            List<MyCart> mycart = getMyCart(drs, out ids);
            IDictionary<string, object> arr = new Dictionary<string, object>();
            arr.Add("Valid", mycart);
            arr.Add("NoValid", Nomycart);
            ViewData["cartids"] = ids;
            ViewData["encryptString"] = EncryptHelper.EncryptMd5(ids + WebConfig.token);
            
            return View(arr);
        }
        #endregion
    }
}
